package com.meituan.catering.management.product.biz.service.impl;

import com.meituan.catering.management.common.model.biz.UserContextBO;
import com.meituan.catering.management.product.api.http.model.request.*;
import com.meituan.catering.management.product.biz.model.ProductBO;
import com.meituan.catering.management.product.biz.model.converter.ProductBOConverter;
import com.meituan.catering.management.product.biz.service.ProductAccessoryBizService;
import com.meituan.catering.management.product.biz.service.ProductBizService;
import com.meituan.catering.management.product.biz.service.ProductMethodBizService;
import com.meituan.catering.management.product.biz.service.ProductOperateService;
import com.meituan.catering.management.product.dao.mapper.ProductMapper;
import com.meituan.catering.management.product.dao.model.ProductDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class ProductOperateServiceImpl implements ProductOperateService {
    private final static Boolean UP_PRODUCT=true;
    private final static Boolean DOWN_PRODUCT=false;
    @Resource
    ProductMapper productMapper;
    @Resource
    ProductAccessoryBizService productAccessoryBizService;
    @Resource
    ProductMethodBizService productMethodBizService;
    @Resource
    ProductBizService productBizService;
    @Resource
    TransactionTemplate transactionTemplate;

    /**
     * 创建请求  拆分成三个DO 分别插入
     * @param userContextBO
     * @param request
     * @return
     */
    @Override
    public ProductBO create(UserContextBO userContextBO, CreateProductHttpRequest request) {
        ProductDO productDO = this.buildProductDO(userContextBO, request);
        /**
         * 插入菜品 做法组集 加料组集
         */
        ProductBO productBO= transactionTemplate.execute(transactionTemplate->{
            try {
                int insert=productMapper.insert(productDO);
                if(insert>0){
                    if(request.getAccessoryGroups().size()!=0){
                         this.productAccessoryBizService.insetList(userContextBO, request.getAccessoryGroups(), productDO.getId());
                    }
                    if (request.getMethodGroups().size()!=0){
                         this.productMethodBizService.insetList(userContextBO, request.getMethodGroups(), productDO.getId());
                    }
                    /**
                     * 三个表插入完成后
                     */
                    ProductBO product = this.findProductById(userContextBO, productDO.getId());
                    product.getMethodGroups().addAll(productMethodBizService.findAllByProductId(userContextBO.getTenantId(),productDO.getId()));
                    product.getAccessoryGroups().addAll(productAccessoryBizService.findAllByProductId(userContextBO.getTenantId(),productDO.getId()));

                    return product;
                }
            }catch (Exception e){
                /**
                 * 出现错误回滚
                 */
                transactionTemplate.setRollbackOnly();
            }
           return null;

       });
        return productBO;
    }

    /**
     * 修改商品
     * 1.修改商品表本身
     * 2.删除关联了商品id的方法组集合 加料组集合
     * 3.插入需要更新的方法加料
     */
    @Override
    public ProductBO update(UserContextBO userContextBO, Long id, UpdateProductHttpRequest request) {
        /**
         * 构建更新DO
         */
        ProductDO productDO = this.buildProductDO(userContextBO, request,id);
        ProductBO productBO = transactionTemplate.execute(transactionStatus -> {
            try {
                int i = productMapper.updateSelective(productDO);
                if (i>0){
                    /**
                     * 商品本身表修改成功    删除 加料组 方法组
                     */
                     this.productAccessoryBizService.delete(userContextBO, id);
                     this.productMethodBizService.delete(userContextBO, id);
                    /**
                     * 添加新的方法组 加料组
                     */
                    this.productAccessoryBizService.updataList(userContextBO, request.getAccessoryGroups(), id);
                    this.productMethodBizService.updataList(userContextBO, request.getMethodGroups(), id);
                    /**
                     * 查询更新后的值
                     */
                    ProductBO product = this.findProductById(userContextBO, id);
                    product.getMethodGroups().addAll(productMethodBizService.findAllByProductId(userContextBO.getTenantId(),id));
                    product.getAccessoryGroups().addAll(productAccessoryBizService.findAllByProductId(userContextBO.getTenantId(),id));
                    return product;
                }
            } catch (Exception e) {
                /**
                 * 异常回滚
                 */
               transactionStatus.setRollbackOnly();
               log.error("修改商品异常");
            }
            /**
             * 代表修改失败
             */
            //return null;
            throw new IllegalArgumentException("商品修改失败");
        });
       return productBO;
    }

    /**
     * 商品上架
     * @param userContextBO
     * @param id
     * @param request
     * @return
     */
    @Override
    public ProductBO enable(UserContextBO userContextBO, Long id, EnableProductHttpRequest request) {
        /**
         * 先查询是否是下架状态
         */
        ProductBO productBO = productBizService.findById(userContextBO, id);
        Integer enabled = productBO.getEnabled();
        Integer version=productBO.getVersion();
        if(enabled!=null && enabled.equals(0))
        {
            productBO= transactionTemplate.execute(transactionStatus -> {
                int i = productMapper.changeEnabledById(userContextBO.getTenantId(), id, 1,version);
                if (i>0)
                {
                    //上架成功
                    return productBizService.findById(userContextBO, id);

                }else {
                    transactionStatus.setRollbackOnly();
                    throw  new IllegalStateException("上架菜品失败");
                }
            });
        }else {
            throw new IllegalStateException("该商品已上架");
        }
        return productBO;
    }

    @Override
    public ProductBO disable(UserContextBO userContextBO, Long id, DisableProductHttpRequest request) {
        /**
         * 先查询是否是上架状态
         */
        ProductBO productBO = productBizService.findById(userContextBO, id);
        Integer enabled = productBO.getEnabled();
        Integer version=productBO.getVersion();
        if(enabled!=null && enabled.equals(1))
        {
            productBO= transactionTemplate.execute(transactionStatus -> {
                int i = productMapper.changeEnabledById(userContextBO.getTenantId(), id, 0,version);
                if (i>0)
                {
                    return productBizService.findById(userContextBO, id);
                    //上架成功
                }else {
                    transactionStatus.setRollbackOnly();
                    throw  new IllegalStateException("下架菜品失败");
                }
            });
        }else {
            throw new IllegalStateException("该商品已下架");
        }

        return productBO;
    }

    public ProductBO findProductById(UserContextBO userContextBO,Long id){
        ProductDO productDO = productMapper.findById(userContextBO.getTenantId(), id);
        if (productDO!=null){
           return  ProductBOConverter.fromDO(productDO);
        }else {
           throw new IllegalArgumentException("没查询到商品信息");
        }
    }
    /**
     * 更新 菜品构建方法
     */
    private ProductDO buildProductDO(UserContextBO userContextBO, UpdateProductHttpRequest request,Long id){
        ProductDO productDO=new ProductDO();
        productDO.setId(id);
        productDO.setTenantId(userContextBO.getTenantId());
        productDO.setLastModifiedBy(userContextBO.getUserId());
        productDO.setLastModifiedAt(new Date());
        productDO.setVersion(request.getVersion());

        /**
         * 设置初始化菜品状态
         */
        productDO.setEnabled(UP_PRODUCT?1:0);
        productDO.setDescription(request.getDescription());
        productDO.setName(request.getName());
        productDO.setIncreaseSalesQuantity(request.getIncreaseSalesQuantity());
        productDO.setMinSalesQuantity(request.getMinSalesQuantity());
        productDO.setUnitOfMeasure(request.getUnitOfMeasure());
        productDO.setUnitPrice(request.getUnitPrice());
        /**
         * 设置初始化版本号
         */

        return productDO;
    }


    /**
     * 创建菜品构建方法
     * @param userContextBO
     * @param request
     * @return
     */
    private ProductDO buildProductDO(UserContextBO userContextBO, CreateProductHttpRequest request){
        ProductDO productDO=new ProductDO();
        productDO.setTenantId(userContextBO.getTenantId());
        productDO.setCreatedBy(userContextBO.getUserId());
        productDO.setCreatedAt(new Date());
        /**
         * 设置初始化菜品状态
         */
        productDO.setEnabled(UP_PRODUCT?1:0);
        productDO.setDescription(request.getDescription());
        productDO.setName(request.getName());
        productDO.setIncreaseSalesQuantity(request.getIncreaseSalesQuantity());
        productDO.setMinSalesQuantity(request.getMinSalesQuantity());
        productDO.setUnitOfMeasure(request.getUnitOfMeasure());
        productDO.setUnitPrice(request.getUnitPrice());
        /**
         * 设置初始化版本号
         */
        productDO.setVersion(1);
        return productDO;
    }




}
